﻿using System;
using System.Configuration;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

using TravelSite.Code;
using TravelSite.DAL;
using TravelSite.DAL.Repositories;
using TravelSite.Entities;

namespace TravelSite
{
    public partial class ContractView : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(Code))
            {
                AlertAndClear("Unknown page!");
                return;
            }

            if (!IsPostBack)
            {
                using (var repo = RepositoryFactory.ResolveRepository<ContractRepository>())
                {
                    Contract itm = repo.Find(Code);
                    if (itm == null)
                    {
                        AlertAndClear("Unknown contract!");
                        return;
                    }

                    if ((itm.StatusValue != ContractStatus.Viewed) && (itm.StatusValue != ContractStatus.Signed))
                    {
                        repo.SetStatus(itm.ContractId, "Viewed", GetIPAddress(), null);
                        itm.StatusValue = ContractStatus.Viewed;
                    }

                    if (itm.StatusValue == ContractStatus.Viewed)
                    {
                        btnView.Visible = true;
                        btnPrint.Visible = false;
                        btnSavePDF.Visible = false;
                        btnClose.Visible = false;
                    }
                    else
                    {
                        btnView.Visible = false;
                        btnPrint.Visible = true;
                        btnSavePDF.Visible = true;
                        btnClose.Visible = true;
                    }

                    btnSavePDF.HRef = string.Format("ContractToPdf.aspx?c={0}&d=1", itm.ContractId.ToString());
                    btnClose.Attributes.Add("onclick", "window.open('javascript:window.open(\"\", \"_self\", \"\");window.close();', '_self');");
                    btnPrint.Attributes.Add("onclick", string.Format("printIframe('{0}')", frameDocument.ClientID));
                    frameDocument.Attributes.Add("src", string.Format("ContractToPdf.aspx?c={0}", itm.ContractId.ToString()));
                }
            }
        }

        protected void btnView_Click(object sender, EventArgs e)
        {
            using (var repo = RepositoryFactory.ResolveRepository<ContractRepository>())
            {
                Contract itm = repo.Find(Code);
                if (itm == null)
                {
                    ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "Alert", string.Format("alert('{0}');", "Unknown contract!"), true);
                    return;
                }
                string pin = repo.SetStatus(itm.ContractId, "Signed", GetIPAddress(), null, itm.ContactId);
                if (!string.IsNullOrEmpty(pin))
                {
                    pin = SendPin(itm.ContactId, pin);
                    ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "Alert", string.Format("alert('{0}');", pin), true);
                }
                else
                {
                    ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "Alert", string.Format("alert('{0}');", "Error creating pin"), true);
                }
                btnView.Visible = false;
                
                btnPrint.Visible = true;
                btnSavePDF.Visible = true;
                btnClose.Visible = true;
            }
        }

        public string SendPin(int contactId, string pin)
        {
            string contactEmail = "";
            Contact ct = null;

            using (ContactRepository repo = new ContactRepository())
            {
                ct = repo.Find(contactId);
                contactEmail = ct.Email;
            }

            if (string.IsNullOrEmpty(contactEmail))
                return "Email is not specified for contact!";

            string temlatePath = Path.Combine(Server.MapPath("~/Files/Templates/YVD App PIN Email.txt"));
            if (!File.Exists(temlatePath))
                return "Email template file is not exists!";
            string msgBody = File.ReadAllText(temlatePath);
            msgBody = msgBody.Replace("%ContractLink%", pin).Replace("%First Name%", ct.FirstName).Replace("%Last Name%", ct.LastName);
            try
            {
                Common.SendEmail(contactEmail, "", "Ultimate Vacation Experience App PIN", msgBody);
                return "Pin Sent!";
            }
            catch (Exception e)
            {
                return "Error occurs on email sending! (" + e.Message + ")";
            }
        }

        public string Code
        {
            get
            {
                string result = "";
                if (!string.IsNullOrEmpty(Request.QueryString["code"]))
                    result = Request.QueryString["code"];
                return result;
            }
        }
    }
}